<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once('admin'.EXT);

class Course extends Admin {
    
    function __construct()
    {
        parent::__construct();
        $this->load->model(array('course_model','cat_course_model'));
        $this->load->helper(array('upload','text'));		
        $this->data['cat_course']	=	$this->cat_course_model->order_by('sort','ASC')->get_all();
    }
    
    function index()
    {
        $row = $this->db->select()->from("config")->get()->row();
        $result	=	$this->course_model->get_by_limit();
        $rows	=	$result['rows'];
        
        $this->data['row']  =   $row;
        
        if($_SERVER['REQUEST_METHOD']=='POST')
        {
            $_data = array(
                'addr'  =>  $this->input->post('addr'),
                'tel'  =>  $this->input->post('tel'),
                'fax'  =>  $this->input->post('fax'),
                'email' => $this->input->post('email')
            );
            if($row){
                $this->db->update('config',$_data);
                $this->db->where('id',$row->id);
            }
            else{
                $this->db->insert('config',$_data);
            }
            redirect(admin_url('config'));
        }
        
        foreach($rows as $k => $v)
        {
        	$cat	=	$this->cat_course_model->get_by('id',$v->cat_id);
        	if($cat)
        		$rows[$k]->cat_name	=	$cat->name;
        	else 
        		$rows[$k]->cat_name	=	'';
        }
        
        $this->data['rows']	=	$rows;
        $this->data['pagnav']	=	'';
        $this->data['tpl_file']	= 'course/index';
        $this->load->view('layout/default', $this->data);
    }
    
    //Add new course
    function add()
    {
    	if($_SERVER["REQUEST_METHOD"] == 'POST')
    	{
    		$this->form_validation->set_message('required', '%s không hợp lệ!');
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');
    		$this->form_validation->set_rules('txt_desc', 'Mô tả', 'required|trim|xss_clean');
    		$title	=	$this->input->post('txt_title');//ascii_link
    		$title_link	=	ascii_link($title);
    		$hot	=	($this->input->post('host') == 1 ? 1 : 0);
    		$active	=	($this->input->post('active') == 1 ? 1 : 0);
    		$cat_id	=	$this->input->post('cat_course');

    		if($this->form_validation->run() == TRUE)
            {            	
            	$data	=	array(
            		'title'	=>	$title,
            		'title_link'	=>	$title_link,
            		'desc'	=>	$this->input->post('txt_desc'),
            		'content'	=>	$this->input->post('txt_content'),
            		'time_create'	=>	time(),
            		'hot'	=>	$hot,
            		'active'	=>	$active,
            		'cat_id'	=>	$cat_id
            	);
            	
            	if(isset($_FILES["image"]["name"]) && $_FILES["image"]["name"] != '') 
            	{
            		// Upload images
            		$album_dir = 'uploads/course/';
            		if(!is_dir($album_dir))
            		{            			
            			create_dir($album_dir);	
            		}
            		
            	    $ext = get_ext($_FILES["image"]["name"]);
                    if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
                    	continue;
                    }
                   
            		if($_FILES['image']['error'] === 0) 
            	    {            	    	
				        $new_path = $album_dir.$_FILES["image"]["name"];
				        move_uploaded_file($_FILES["image"]['tmp_name'], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);   			            	    
            			$data['image']	=	$this->_create_thumb($new_path);
            	    }
            	                	        	
            	}
            	
            	if($this->course_model->insert($data))
            	{
            		redirect(admin_url('course'));
            	}
            }
            else
            {
            	$this->message->add('error',validation_errors());
            }
    	}
    	$this->data['tpl_file']	= 'course/update';
        $this->load->view('layout/default', $this->data);
    }
    //End add new course
    
    /*
     * @method: edit course
     * @param: id
     * @return: 
     */
    
    function edit($id = null)
    {
    	$row	=	$this->course_model->get_by('id',$id);
    	if($row)
    	{
    		if($_SERVER['REQUEST_METHOD'] == 'POST')
    		{
    			$title	=	$this->input->post('txt_title');//ascii_link
    			$title_link	=	ascii_link($title);
    			$hot	=	($this->input->post('host') == 1 ? 1 : 0);
    			$active	=	($this->input->post('active') == 1 ? 1 : 0);
    			$cat_id	=	$this->input->post('cat_course');
    			
    			$data	=	array(
            		'title'	=>	$title,
            		'title_link'	=>	$title_link,
            		'desc'	=>	$this->input->post('txt_desc'),
            		'content'	=>	$this->input->post('txt_content'),
            		'time_update'	=>	time(),
    				'hot'	=>	$hot,
    				'active'	=>	$active,
    				'cat_id'	=>	$cat_id
            	);
            	
            	//@Case have image
            	if(isset($_FILES["image"]["name"]) && $_FILES["image"]["name"] != '') 
            	{
            		// Upload images
            		$album_dir = 'uploads/course/';
            		if(!is_dir($album_dir))
            		{            			
            			create_dir($album_dir);	
            		}
            		
            	    $ext = get_ext($_FILES["image"]["name"]);
                    if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
                    	continue;
                    }
                   
            		if($_FILES['image']['error'] === 0) 
            	    {            	    	
				        $new_path = $album_dir.$_FILES["image"]["name"];
				        move_uploaded_file($_FILES["image"]['tmp_name'], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);   			            	    
            			$data['image']	=	$this->_create_thumb($new_path);
            	    }
            	                	        	
            	}
            	//End case have image
            	
            	if($this->course_model->update($row->id,$data))
            	{
            		redirect(admin_url('course'));
            	}
    		}
    	}
    	
    	$this->data['row']	=	$row;
    	$this->data['tpl_file']	= 'course/update';
        $this->load->view('layout/default', $this->data);
    }
    //End edit course with id
    
    //Update cat course
    function update_cat($id = null)
    {
    	$input_form	=	array();
    	$row	=	array();
    	if($id){
    		$row	=	$this->cat_course_model->get_by('id',$id);
    		$input_form	=	$row;
    	}
    	if($_SERVER['REQUEST_METHOD'] == 'POST')
    	{
    		$name	=	$this->input->post('name');
    		$name_link	=	ascii_link($name);
    		$active		=	($this->input->post('active') == 1 ? 1 : 0);
    		$sort		=	(int)$this->input->post('sort');
    		$data	=	array(
    			'name'	=>	$name,
    			'name_ascii'	=>	$name_link,
    			'active'	=>	$active,
    			'sort'		=>	$sort
    		);
    		
    		$input_form->name	=	$name;
    		$input_form->active	=	$active;
    		$input_form->sort	=	$sort;
    		
    		$suc	=	false;
    		
    		//if have row then update
    		if($row)
	    	{
	    		if($this->cat_course_model->update($row->id,$data)){
	    			$suc = true;
	    		}
	    	}//end update
	    	else 
	    	{//add new
	    		if($this->cat_course_model->insert($data))
	    		{
	    			$suc = true;
	    		}
	    	}//end add new
	    	
	    	//if suc == true then redirect to index cat course
	    	if($suc == true)
	    	{
	    		redirect(action_link('list_cat'));
	    	}
    	}
    	
    	$this->data['input_form']	=	$input_form;
    	$this->data['tpl_file']	= 'course/update_cat';
        $this->load->view('layout/default', $this->data);	
    }
    //End update cat course
    
    function list_cat()
    {
    	$this->data['tpl_file']	= 'course/list_cat';
        $this->load->view('layout/default', $this->data);	
    }
    
    /*
     * method: create thumb
     * param: path image
     * return: path/image_name
     */
	function _create_thumb($img_path = '')
	{
		$sizes = config_item('thumb_img_course');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		$temp	=	explode('.',$pathinfo['basename']);
		$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}
		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}
	//End create thumb
}